<?php
namespace app\common\enum;

class Model extends Base
{
	protected static $options = [];
    protected static $showOptions = [];
    protected static $model = '';
    protected static $show_list = 'show_list';

    protected static $pk   = 'id';
    protected static $name = 'name';

    protected static $uid = 'uid';
    protected static $upk = 'id';

    public static function query_options($fun = null) {
        $model = static::$model;
        if(is_string($model)) {
            static::$model = $model = loadModel($model);
        }
        if(is_callable($fun)) {
            $fun($model);
        }
        return $model->column(static::$pk . ',' . static::$name);
    }

    public static function get_options($fun = null) {
        $name = static::class;
        if($fun) {
            return static::query_options($fun);
        }
        if(!isset(static::$options[$name])) {
            static::$options[$name] = static::query_options();
        }
        return static::$options[$name];
    }

    public static function get_user_options($fun = null) {
        $login = loadStorage('login');
        $user = $login->getCurrentUser();
        $post = [];
        $post[static::$uid] = $user[static::$upk];

        return static::query_options(function($model) use ($post, $fun) {
            $model->where($post);
            if(is_callable($fun)) {
                $fun($model);
            }
        });
    }

    public static function get_show_options($fun = null) {
        $name = static::class;
        $model = static::$model;
        $show_list = static::$show_list;
        if(!method_exists($model, $show_list)) {
            return static::get_options($fun);
        }
        if(!isset(static::$showOptions[$name])) {
            static::$showOptions[$name] = static::query_options(function($model) {
                $model->$show_list();
                if(is_callable($fun)) {
                    $fun($model);
                }
            });
        }
        return static::$showOptions[$name];
    }

}